package com.siyoumi.app.config;

import com.siyoumi.util.XDate;
import com.siyoumi.util.XStr;
import com.siyoumi.util.entity.ThreadLocalData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import javax.annotation.PostConstruct;
import java.util.concurrent.*;

@Slf4j
@Configuration
@EnableAsync
public class ThreadPoolConfig {
    static private ThreadPoolConfig ins;

    static public ThreadPoolConfig getIns() {
        return ins;
    }

    @PostConstruct
    private void setStatic() {
        ins = this;
    }

    @Bean("ThreadPools")
    public ThreadPoolTaskExecutor threadPools() {
        //ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
        //        1,  // 核心线程数量
        //        1,              //最大线程数
        //        5,             //空闲临时线程最大存活时间（数值）
        //        TimeUnit.SECONDS,//空闲临时线程最大存活时间（单位）
        //        new ArrayBlockingQueue<>(1),//任务队列，也就是一个堵塞队列，也可以使用LinkedBlockingQueue这个阻塞队列
        //        Executors.defaultThreadFactory(),//用线程池工具类Executors创建线程的工厂
        //        new ClientPolicy()//任务的拒绝策略中其中一个，丢弃任务并抛出RejectedExecutionException
        //);

        ThreadPoolTaskExecutor pool = new ThreadPoolTaskExecutor();
        // 核心线程数,线程池创建时候初始化的线程数
        pool.setCorePoolSize(1);
        // 最大线程数,线程池最大的线程数，只有在缓冲队列满了之后才会申请超过核心线程数的线程
        pool.setMaxPoolSize(1);
        // 缓冲队列,用来缓冲执行任务的队列
        pool.setQueueCapacity(0);
        // 允许线程的空闲时间,当超过了核心线程之外的线程在空闲时间到达之后会被销毁
        pool.setKeepAliveSeconds(60);
        // 线程池名的前缀
        pool.setThreadNamePrefix("Thread-");
        // 缓冲队列满了之后的拒绝策略,由调用线程处理（一般是主线程）
        pool.setRejectedExecutionHandler(new ClientPolicy());
        pool.initialize();
        log.debug("threadPools init");
        return pool;
    }
}

@Slf4j
class ClientPolicy
        implements RejectedExecutionHandler {
    /**
     * Creates a {@code DiscardPolicy}.
     */
    public ClientPolicy() {
    }

    /**
     * Does nothing, which has the effect of discarding task r.
     *
     * @param r the runnable task requested to be executed
     * @param e the executor attempting to execute this task
     */
    public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
        log.error("Thread error: {}-{}", ThreadLocalData.get("id", ""), XDate.toDateTimeString());
    }
}